﻿
namespace n_WorkForm
{
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

using n_ControlCenter;
using n_FileTabPage;
using n_LaterFilesManager;
using n_LaterFilePanel;
using n_myTabControl;
using n_OS;
using n_UnitTreeView;
using n_UseFileList;
using n_WordList;
using T;
using i_Compiler;
using n_GUIcoder;
using n_ISP;
using n_AVRdude;

using n_ErrorListBox;
using n_ET;
using n_OutputBox;
using n_ArduinoSimPanel;
using System.IO;
using System.Collections;

public partial class WorkForm : Form
{
	//Image NewFileIcon;
	//Image OpenFileIcon;
	//Image ClearFileIcon;
	
	//myTabControl TexttabControl;
	
	bool NullTab = false;
	
	public Panel 扩展信息窗口;
	public Label 模块信息按键;
	
	string AFileName;
	RichTextBox LoadTextBox;
	
	ArduinoSimPanel APanel;
	
	FileTabPage LastSelectedTab;
	
	//构造函数
	public WorkForm( string StartFileName )
	{
		//界面属性设置
		InitializeComponent();
		
		ISP.ProgressStep += this.ProgressStep;
		ISP.ISPStep += this.ISPStep;
		AVRdude.ProgressStep += this.ProgressStep;
		AVRdude.ISPStep += this.ISPStep;
		
		SetDefaultMessage();
		
		//NewFileIcon = Image.FromFile( OS.SystemRoot + "Resource" + OS.PATH_S + "WorkBox" + OS.PATH_S + "NewFile.ico" );
		//OpenFileIcon = Image.FromFile( OS.SystemRoot + "Resource" + OS.PATH_S + "WorkBox" + OS.PATH_S + "OpenFile.ico" );
		//ClearFileIcon = Image.FromFile( OS.SystemRoot + "Resource" + OS.PATH_S + "WorkBox" + OS.PATH_S + "ClearFile.ico" );
		
		扩展信息窗口 = this.panelExtendMesBox;
		扩展信息窗口.Visible = false;
		模块信息按键 = this.buttonExtendButton;
		
		comboBoxChip.SelectedIndex = -1;
		
		this.splitContainerMain.Dock = DockStyle.Fill;
		
		//TexttabControl = new myTabControl();
		//TexttabControl.Dock = DockStyle.Fill;
		//TexttabControl.SendToBack();
		//this.splitContainerMain.Panel2.Controls.Add( TexttabControl );
		//this.splitContainer1.Panel1.Controls.Add( TexttabControl );
		
		this.tabControl1.Controls.Add( OutputBox.Init( this.tabControl1 ) );
		this.tabControl1.Controls.Add( ErrorListBox.Init( this.tabControl1 ) );
		splitContainer1.SplitterDistance = splitContainer1.Height;
		
		LoadTextBox = new RichTextBox();
		
		//近期文件列表初始化
		this.Controls.Remove( this.panel1 );
		LaterFilePanel p = new LaterFilePanel();
		
		//创建默认标签栏
		if( NullTab ) {
			FileTabPage filePanel = new FileTabPage( TexttabControl );
			filePanel.Controls.Add( p );
		}
		
		//this.splitContainerMain.Panel1.Controls.Add( UnitTreeView.UnitTree );
		//Compiler.uTreeView = UnitTreeView.UnitTree;
		
		AFileName = StartFileName;
		
		A.AddNewFile += this.AddNewFile;
		
		APanel = new ArduinoSimPanel();
		n_Interface.AVM.D_ModuleWrite += APanel.ModuleWrite;
		n_Interface.AVM.D_ModuleRead += APanel.ModuleRead;
		
		//this.splitContainerMain.SplitterDistance = 0;
		
		//splitContainerMain.Panel1.Controls.Add( APanel );
		
		cnode = treeView.Nodes;
		A_FindFile( n_OS.OS.SystemRoot + "Resource\\lbword\\" );
	}
	
	//运行
	public void Run()
	{
		Visible = true;
	}
	
	//添加新文件
	public void AddNewFile( string FileName )
	{
		foreach( FileTabPage t in TexttabControl.Controls ) {
			if( t.ctext != null && t.ccode.PathAndName == FileName ) {
				LastSelectedTab = t;
				this.TexttabControl.SelectTab( t );
				this.TexttabControl.Refresh();
				t.SetCurrent();
				return;
			}
		}
		//int N = TexttabControl.TabCount;
		//FileTabPage NullPanel = (FileTabPage)TexttabControl.TabPages[N - 1];
		//TexttabControl.TabPages.Remove( NullPanel );
		FileTabPage filePanel = new FileTabPage( FileName, TexttabControl, null );
		//TexttabControl.Controls.Add( NullPanel );
		
		if( NullTab ) {
			int N = TexttabControl.TabCount;
			FileTabPage NullPanel = (FileTabPage)TexttabControl.TabPages[N - 2];
			TexttabControl.TabPages[N - 1] = NullPanel;
			TexttabControl.TabPages[N - 2] = filePanel;
			TexttabControl.SelectedIndex = N - 2;
		}
		
		LastSelectedTab = filePanel;
		
		//需要加上这一项
		filePanel.SetCurrent();
	}
	
	//关闭窗体
	//注意这里不要用: TexttabControl.Controls, 因为 Controls[0] 不代表分页中的第一个,
	//而只是最初添加的顺序
	public bool CanClose()
	{
		while( TexttabControl.TabPages.Count > 0 ) {
			FileTabPage t = (FileTabPage)TexttabControl.TabPages[ 0 ];
			
			if( t.ctext != null && !t.TryClose() ) {
				return false;
			}
		}
		return true;
	}
	
	void ISPStep( string Mes )
	{
		this.Text = Mes;
	}
	
	void ProgressStep( int Max, int c )
	{
		if( c == Max - 1 ) {
			SetDefaultMessage();
		}
		else {
			this.Text = "已下载: " + (c * 100 / Max) + "%";
		}
	}
	
	//设置默认标题
	void SetDefaultMessage()
	{
		this.Text = "crux IDE";
	}
	
	//加载事件
	void Form_Load( object sender, EventArgs e )
	{
		//Application.EnableVisualStyles();
		
		//正常启动
		//ControlPad.eyeTimer.Enabled = true;
		//ControlPad.ShowImage();
		
		//判断是否双击程序本身打开
		if( AFileName != null ) {
			AddNewFile( AFileName );
			LaterFilesManager.AddFile( AFileName );
		}
	}
	
	//关闭窗体事件
	void Form_Closing( object sender, CancelEventArgs e )
	{
		if( A.isGForm ) {
			e.Cancel = true;
			Visible = false;
			return;
		}
		if( !CanClose() ) {
			e.Cancel = true;
			return;
		}
	}
	
	void ButtonExtendReplaceClick(object sender, EventArgs e)
	{
		if( ControlCenter.isBusy() ) {
			return;
		}
		try {
		panelExtendMesBox.Visible = false;
		string Mes = ((Label)sender).Name;
		
		//处理板子类型和语言
		Mes = Mes.Replace( GUIcoder.GetSysDefine( "chip" ), ((Label)sender).Text );
		Mes = Mes.Replace( GUIcoder.GetSysDefine( "language" ), ((Label)sender).Text );
		Mes = Mes.Replace( GUIcoder.GetSysDefine( "run" ), ((Label)sender).Text );
		OpenFile( Mes );
		}
		catch {
			A.CodeErrBox.Run( "出错了" );
		}
	}
	
	void Label打开文件Click(object sender, EventArgs e)
	{
		if( ControlCenter.isBusy() ) {
			return;
		}
		try {
		panelExtendMesBox.Visible = false;
		string Mes = ((Label)sender).Name;
		
		OpenFile( Mes );
		}
		catch {
			A.CodeErrBox.Run( "出错了" );
		}
	}
	
	void ButtonExtentClick(object sender, EventArgs e)
	{
		if( ControlCenter.isBusy() ) {
			return;
		}
		try {
			panelExtendMesBox.Visible = false;
			string Mes = ((Label)sender).Name;
		
			int Index = int.Parse( ((Label)sender).Name );
			int FileIndex = WordList.GetFileIndex( Index );
			string FilePath = UseFileList.GetPath( FileIndex );
			
			if( !Compiler.FileExists( FilePath ) ) {
				Compiler.Show( "文件不存在: " + FilePath );
				return;
			}
			
			int Line = WordList.GetLine( Index );
			int StartIndex = WordList.GetColumn( Index );
			int Length = WordList.GetWord( Index ).Length;
			LaterFilesManager.AddFile( FilePath );
			AddNewFile( FilePath );
			T.ctext.SelectionStart = T.ctext.Text.Length;
			T.ctext.SelectionStart = T.ctext.GetFirstCharIndexFromLine( Line ) + StartIndex;
			T.ctext.SelectionLength = Length;
		}
		catch {
			A.CodeErrBox.Run( "无法跳转到组件的源代码, 请点击\"检查语法按钮\"后再试试" );
		}
	}
	
	//打开指定的文件
	void OpenFile( string FilePath )
	{
		if( !Compiler.FileExists( FilePath ) ) {
			Compiler.Show( "文件不存在: " + FilePath );
			return;
		}
		LaterFilesManager.AddFile( FilePath );
		AddNewFile( FilePath );
	}
	
	//==================================================================
	
	void LabelCheckClick(object sender, EventArgs e)
	{
		n_Compiler.Compiler.SimTempSource = null;
		G.ccode.SetCode( T.ctext.Text );
		G.ccode.Save();
		ControlCenter.Check( true, false );
	}
	
	void LabelToolClick(object sender, EventArgs e)
	{
		if( T.ToolBox == null ) {
			T.ControlInit();
		}
		T.ToolBox.Run();
	}
	
	void ButtonNewClick(object sender, EventArgs e)
	{
		//保存文件对话框
		SaveFileDialog SaveFileDlg = new SaveFileDialog();
		SaveFileDlg.Filter = "文本类型文件 | *.txt";
		SaveFileDlg.Title = "保存文件";
		
		SaveFileDlg.FileName = "我的小程序.txt";
		DialogResult dlgResult = SaveFileDlg.ShowDialog();
		if(dlgResult == DialogResult.OK) {
			string FilePath = SaveFileDlg.FileName;
			if( !FilePath.ToLower().EndsWith( ".txt" ) ) {
				FilePath += ".txt";
			}
			VIO.SaveTextFile( FilePath, "" );
			
			//添加到近期文档列表
			LaterFilesManager.AddFile( FilePath );
			
			//创建文档
			AddNewFile( FilePath );
		}
	}
	
	void ButtonSaveClick(object sender, EventArgs e)
	{
		if( T.ctext == null ) {
			A.CodeErrBox.Run( "无法保存, 当前未打开任何文件" );
			return;
		}
		G.ccode.SetCode( T.ctext.Text );
		G.ccode.Save();
	}
	
	void ButtonOpenClick(object sender, EventArgs e)
	{
		//打开文件对话框
		OpenFileDialog OpenFileDlg = new OpenFileDialog();
		OpenFileDlg.Filter = "所有类型文件 | *.*";
		OpenFileDlg.Title = "请选择文件";
		//OpenFileDlg.InitialDirectory = n_OS.OS.SystemRoot + "example\\python";
		
		DialogResult dlgResult = OpenFileDlg.ShowDialog();
		if(dlgResult == DialogResult.OK) {
			
			//添加到近期文档列表
			LaterFilesManager.AddFile( OpenFileDlg.FileName );
			
			//根据文件类型打开文件
			T.OpenFileAsType( OpenFileDlg.FileName );
		}
	}
	
	void ButtonCompileClick(object sender, EventArgs e)
	{
		n_Compiler.Compiler.SimTempSource = null;
		G.ccode.SetCode( T.ctext.Text );
		G.ccode.Save();
		ControlCenter.Compile( true, false );
	}
	
	void ButtonDownClick(object sender, EventArgs e)
	{
		n_Compiler.Compiler.SimTempSource = null;
		
		//这里应该提供一个默认设置项
		//n_AVRdude.AVRdude.BoardType = n_MainSystemData.SystemData.DefaultBoardType;
		
		if( comboBoxChip.SelectedIndex == -1 ) {
			MessageBox.Show( "下载前请先选择目标主板型号" );
			return;
		}
		if( comboBoxChip.SelectedIndex == 0 ) {
			n_AVRdude.AVRdude.BoardType = "UNO";
		}
		if( comboBoxChip.SelectedIndex == 1 ) {
			n_AVRdude.AVRdude.BoardType = "NANO";
		}
		if( comboBoxChip.SelectedIndex == 2 ) {
			n_AVRdude.AVRdude.BoardType = "644";
		}
		if( comboBoxChip.SelectedIndex == 3 ) {
			n_AVRdude.AVRdude.BoardType = "2560";
		}
		if( comboBoxChip.SelectedIndex == 4 ) {
			MessageBox.Show( "已在当前目录下创建hex文件， 请使用STC-ISP或其他方式下载程序到芯片上" );
			return;
		}
		
		G.ccode.SetCode( T.ctext.Text );
		G.ccode.Save();
		ControlCenter.CompileAndDown( true, false );
	}
	
	void ButtonMesClick(object sender, EventArgs e)
	{
		if( T.MesBox == null ) {
			T.MesBox = new n_MesForm.MesForm();
		}
		T.MesBox.Run();
	}
	
	//==================================================================
	
	void TabControl1Click(object sender, EventArgs e)
	{
		T.ShowMes();
	}
	
	void ButtonMouseEnter(object sender, EventArgs e)
	{
		Label l = (Label)sender;
		//l.BorderStyle = BorderStyle.FixedSingle;
		labelButtonMes.Text = l.Tag.ToString();
	}
	
	void ButtonMouseLeave(object sender, EventArgs e)
	{
		Label l = (Label)sender;
		l.BorderStyle = BorderStyle.None;
		labelButtonMes.Text = "";
	}
	
	void 关闭当前文档ToolStripMenuItemClick(object sender, EventArgs e)
	{
		if( T.ctext == null ) {
			A.CodeErrBox.Run( "无法关闭文件, 现在没有打开的文件" );
			return;
		}
		FileTabPage FT = (FileTabPage)TexttabControl.SelectedTab;
		int Index = TexttabControl.SelectedIndex;
		if( !FT.TryClose() ) {
			return;
		}
		if( FT == null ) {
			MessageBox.Show( "ERROR" );
		}
		else {
			if( Index == TexttabControl.TabCount - 1 ) {
				Index -= 1;
				if( Index < 0 ) {
					Index = 0;
				}
			}
			TexttabControl.SelectedIndex = Index;
			LastSelectedTab = (FileTabPage)TexttabControl.SelectedTab;
			
			if( LastSelectedTab != null ) {
				((FileTabPage)TexttabControl.SelectedTab).SetCurrent();
			}
		}
	}
	
	void TexttabControlClick(object sender, EventArgs e)
	{
		FileTabPage FT = (FileTabPage)TexttabControl.SelectedTab;
		FT.SetCurrent();
	}
	
	//==================================================================
	
	TreeNodeCollection cnode;
	
	void TreeViewDoubleClick(object sender, EventArgs e)
	{
		string filename= ((TreeView)sender).SelectedNode.Name;
		AddNewFile( filename );
	}
	
	//遍历指定的文件夹中的全部文件
	void A_FindFile( string sSourcePath )
	{
		//在指定目录及子目录下查找文件,在list中列出子目录及文件
		DirectoryInfo Dir = new DirectoryInfo( sSourcePath );
		DirectoryInfo[] DirSub = Dir.GetDirectories();
		
		FileInfo[] files = Dir.GetFiles("*.*", SearchOption.TopDirectoryOnly);
		Array.Sort(files, new FileNameSort());
		
		//遍历当前文件夹中的所有文件
		foreach( FileInfo f in files ) {
			
			string FilePath = Dir + f.ToString();
			
			string text = Path.GetFileName( FilePath );
			text = text.Remove( text.LastIndexOf( "." ) );
			TreeNode tn = cnode.Add( text );
			tn.Name = FilePath;
			//tn.ForeColor = Color.Gray;
		}
		//遍历所有的子文件夹
		foreach( DirectoryInfo d in DirSub ) {
			
			TreeNodeCollection last = cnode;
			TreeNode tn = cnode.Add( d.ToString() );
			tn.Name = "";
			cnode = tn.Nodes;
			
			A_FindFile( Dir + d.ToString() + @"\" );
			
			cnode = last;
		}
	}
	
	public class FileNameSort : IComparer
	{
		//前后文件名进行比较
		public int Compare(object name1, object name2)
		{
			if (null == name1 && null == name2)
			{
				return 0;
			}
			if (null == name1)
			{
				return -1;
			}
			if (null == name2)
			{
				return 1;
			}
			string n1 = name1.ToString();
			string n2 = name2.ToString();
			if( n1[0] == n2[0] ) {
				return 0;
			}
			if( n1[0] < n2[0] ) {
				return -1;
			}
			else {
				return 1;
			}
		}
	}
	
	//==================================================================
	
	Image temp;
	Color tempForeColor;
	Color tempBackColor;
	
	void TextButtonMouseEnter(object sender, EventArgs e)
	{
		Button b = (Button)sender;
		b.Text = b.Name.Remove( 0, 6 );
		temp = b.BackgroundImage;
		b.BackgroundImage = null;
		tempForeColor = b.ForeColor;
		tempBackColor = b.BackColor;
		b.ForeColor = Color.WhiteSmoke;
		b.BackColor = Color.SlateGray;
	}
	
	void TextButtonMouseLeave(object sender, EventArgs e)
	{
		Button b = (Button)sender;
		b.Text = "";
		b.BackgroundImage = temp;
		b.ForeColor = tempForeColor;
		b.BackColor = tempBackColor;
	}
}
}


